<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="js/vue.js"></script>
    <style>
        #app div,#app p{
            width: 100px;
            height: 100px;
            position: absolute;
        }
        .hello{
            background:yellow;
            top:0;
            left:0;
        }
        .world{
            background:blue;
            top:0;
            right:0;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="hello" v-drag>div</div>
        <p class="world" v-drag>p</p>
    </div>
</body>
<script>
    Vue.directive('drag',function(el){
        el.onmousedown=function(e){
            // 获取鼠标点击处分别与元素左边和上边的距离：鼠标位置-元素位置
            var disX=e.clientX-el.offsetLeft;
            var disY=e.clientY-el.offsetTop;

            // 包含在onmousedown里面，表示点击后才移动，为防止鼠标移出元素，所以用document.onmousemove
            document.onmousemove=function(e){
                // 获取移动后元素的位置：鼠标位置-disX/disY
                var l=e.clientX-disX;
                var t=e.clientY-disY;
                el.style.left=l+'px';
                el.style.top=t+'px';
            }

            document.onmouseup=function(e){
                document.onmousemove=null;
                document.onmouseup=null;
            }
        }
    });

    new Vue({
        el:'#app'
    });
</script>
</html>